package cn.com.controller;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.com.redis.RedisUtil;

import com.alibaba.fastjson.JSON;
import com.dubbo.demo.service.TestService;

/**
 * @author liufl
 * @version 创建时间：2017年7月26日 下午2:11:40 类说明
 */
// @RestController
@Controller
@EnableAutoConfiguration
public class TestController {

	Logger log = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private TestService testRestService;

	/**
	 * http://localhost:9080/dubbo_customer_springboot/getSession
	 * (dubbo_customer_springboot是application.properties配置的应用上下文名称)
	 * @param request
	 * @return
	 */
	@RequestMapping(path = "/getSession")
	@ResponseBody
	public String getSessionId(HttpServletRequest request) {
		String sessionId = request.getSession().getId();
		testRestService.say(sessionId);
		return sessionId;
	}

	/*
	 * http://localhost:9080/dubbo_customer_springboot/doLogin/张三
	 * (dubbo_customer_springboot是application.properties配置的应用上下文名称)
	 */
	@RequestMapping("/doLogin/{name}")
	@ResponseBody
	public String getSessionId2(HttpServletRequest request,@PathVariable("name") String userName) {
		String name = "Hello Redis!";
		String res = testRestService.say(name+userName);
		redisStrCache("123", name+userName);
		return res;
	}

	private void redisStrCache(String key, Object value) {
		// String set = RedisUtil.getInstance().strings().set(key,
		// JSON.toJSONString(value));
		// log.info("setResult:"+set);//覆盖插入
		String setNX = RedisUtil.getInstance().strings().setnx(key, JSON.toJSONString(value), "NX", "PX", 60 * 1000l);
		log.info("setNXResult:" + setNX);// 不存在时插入指定毫秒数
		String setXX = RedisUtil.getInstance().strings().setnx(key, JSON.toJSONString(value), "XX", "EX", 60l);
		log.info("setXXResult:" + setXX);// 存在时插入指定秒数
		String get = RedisUtil.getInstance().strings().get(key);// 查看key
		log.info("getResult:" + get);
	}
}
